var divMovil = $('#mover');
var divEstatico = $('#estatico');
var abajo = false;
var originalX;
var originalY;

$('body').mousedown(function(event){
    if(event.target.className.substring(0, 5) == 'movil'){
        divMovil = $('#'+event.target.id);
	console.log('mousedown();'+event.target.id);
	abajo = true;
	originalX = divMovil.position().left;
	originalY = divMovil.position().top;
    }
});

$('body').bind('mousemove', function(event){
    if(abajo){
        var x = event.pageX - parseInt(divMovil.width())/2;
        var y = event.pageY - parseInt(divMovil.height())/2;

        divMovil.css({
            'top' : y + 'px',
            'left' : x + 'px'
        });
    }
});

$('body').bind('mouseup',function(event){
    //validarPosicion(event);
    abajo = false;	
});

$('body').bind('touchstart', function(event){
    if(event.target.className.substring(0, 5) == 'movil'){
        divMovil = $('#'+event.target.id);
	console.log('touchstart();'+event.target.id);
	abajo = true;
	originalX = divMovil.position().left;
	originalY = divMovil.position().top;
    }
});


$('body').bind('touchmove', function(event){
    event.preventDefault();//previene scrolling
    if(abajo){
        var x = event.originalEvent.touches[0].pageX - parseInt(divMovil.width())/2;
        var y = event.originalEvent.touches[0].pageY - parseInt(divMovil.height())/2;
        divMovil.css({
            'top' : y + 'px',
            'left' : x + 'px'
        });
    }
});


$('body').bind('touchend',function(event){
    //validarPosicion(event);
    abajo = false;
});




function validarPosicion(event){
    var x = parseInt(divEstatico.css('left'));
    var y = parseInt(divEstatico.css('top'));

    var width = x + parseInt(divEstatico.width());
    var height = y + parseInt(divEstatico.height());

    var mouseX = event.pageX;
    var mouseY = event.pageY;

    console.log(mouseX + ', ' + mouseY);
    console.log(x + ', ' + y);
    console.log(abajo + ', ' + (mouseX >= x && mouseX <= width && mouseY >= y && mouseY <= height));
    if(abajo){
        if(!(mouseX >= x && mouseX <= width && mouseY >= y && mouseY <= height)){
            divMovil.css({
                    'top' : originalY + 'px',
                    'left' : originalX + 'px'
            });
            //divEstatico.append(divMovil);
        }
    }
}